import { getRobotUseList, getRobotModelList, postRobotAdd, getRobotRemove } from "@/services/languageModel";
import { Form, Input, Button, Table, Icon, Pagination, Modal, message } from "antd";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import robotStyle from "@/pages/robotManagement/robotEdit.less"
import styles from "../index.less"
import BackRouter from "@/pages/robotManagement/backRouter"
import moment from "moment";
import ChangeModel from "./changeModel";
import UsingModelList from "../usingModelList";

class ModelList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      list: [],


      defaultVisible: false,
      defaultList: [],
      defaultQuery: {
        search: "",
      },
      defaultLoading: false,
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  getList = () => {
    const { form: { getFieldsValue }, applicationId } = this.props;
    const { current, size } = this.state;
    this.setState({ loading: true }, async () => {
      let obj = { current, size, name: getFieldsValue().search, applicationId: applicationId };
      const res = await getRobotUseList(obj);
      this.setState({ loading: false, list: res.records, total: res.total })
    })
  }

  doSearch = (current, size) => {
    this.setState({ current, size }, () => {
      this.getList()
    })
  }

  changeModel = row => {
    this.ChangeModel.initModal(row)
  }

  openUseModel = (id) => {
    this.UsingModelList.initModal(id)
  }

  render() {
    const { current, size, total, list, loading, defaultVisible, defaultLoading, defaultList, defaultQuery } = this.state;
    const { form: { getFieldDecorator }, applicationId } = this.props;
    const columns = [
      {
        title: formatMessage({ id: 'largeModel.modelName' }),
        dataIndex: "name",
        width: 200
      },
      {
        title: formatMessage({ id: 'largeModel.createTime' }),
        dataIndex: "createTime",
        width: 200,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: formatMessage({ id: 'largeModel.description' }),
        dataIndex: "comment",
        width: 300
      },
      {
        title: formatMessage({ id: 'largeModel.testStatus' }),
        dataIndex: "status",
        width: 150,
        render: (status, row) => {
          return (
            <div>
              <span>{formatMessage({ id: 'largeModel.passed' })}</span>
            </div>
          )
        }
      },
      {
        title: formatMessage({ id: 'largeModel.action' }),
        width: 200,
        render: (text, row) => {
          return (
            <Button
              type="primary"
              size="small"
              style={{
                background: "#32B16C",
                border: "none"
              }}
              onClick={() => this.removeModel(row)}
            >
              {formatMessage({ id: 'largeModel.remove' })}
            </Button>
          )
        }
      }
    ];
    const modelColumns = [
      {
        title: formatMessage({ id: 'largeModel.modelName' }),
        dataIndex: "name",
        width: 200
      },
      {
        title: formatMessage({ id: 'largeModel.createTime' }),
        dataIndex: "createTime",
        width: 200,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: formatMessage({ id: 'largeModel.testStatus' }),
        dataIndex: "status",
        width: 150,
        render: (status, row) => {
          let text = '';
          switch (status) {
            case 0:
              text = formatMessage({ id: 'largeModel.notTested' });
              break;
            case 1:
              text = formatMessage({ id: 'largeModel.failed' });
              break;
            case 2:
              text = formatMessage({ id: 'largeModel.passed' });
              break;
          };

          return (
            <div>
              <span style={{ color: status == 1 ? 'red' : '' }}>{text}</span>
            </div>
          )
        }
      },
      {
        title: formatMessage({ id: 'largeModel.action' }),
        width: 200,
        render: (text, row) => {
          return row.used ? (
            <Button
              type="primary"
              onClick={() => this.removeModel(row)}
              size="small"
              style={{
                background: "#32B16C",
                border: "none"
              }}
            >
              {formatMessage({ id: 'largeModel.remove' })}
            </Button>
          ) : (
            <Button type="primary" size="small" onClick={() => this.setAddModel(row)}>{formatMessage({ id: 'largeModel.add' })}</Button>
          )
        }
      }
    ];

    return (
      <div>
        <div className={styles.robotTop}>
          <div className={robotStyle.title} style={{ height: '32px', lineHeight: '32px', margin: 0 }}>
            <span>{formatMessage({ id: 'largeModel.configTitle' })}</span>
          </div>
          <div>
            <BackRouter pathname='/enterprise/robotManagement'></BackRouter>
          </div>
        </div>
        <div
          style={{
            marginBottom: 24,
            display: 'flex',
            alignItems: 'center',
            flexWrap: 'wrap',
            justifyContent: 'space-between',
          }}
        >
          <Form layout="inline">
            <Form.Item>
              {getFieldDecorator("search")(<Input placeholder={formatMessage({ id: 'largeModel.placeholder' })} />)}
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={() => this.doSearch(1, size)}>{formatMessage({ id: 'largeModel.search' })}</Button>
            </Form.Item>
          </Form>
          <Button type="primary" icon="plus" onClick={this.setMadelClick}>{formatMessage({ id: 'largeModel.addModelBtn' })}</Button>
        </div>
        <Table
          columns={columns}
          dataSource={list}
          loading={loading}
          scroll={{ x: "auto", y: 606 }}
          rowKey={'id'}
          pagination={false}
        />
        {total > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: 16 }}
            total={total}
            current={current}
            pageSize={size}
            showQuickJumper={true}
            // showSizeChanger={true}
            onChange={this.doSearch}
          // onShowSizeChange={this.doSearch}
          />
        ) : null}

        <ChangeModel onRef={ref => this.ChangeModel = ref} applicationId={applicationId} freshList={this.getList} />

        <UsingModelList onRef={ref => this.UsingModelList = ref} />

        <Modal
          title={formatMessage({ id: 'largeModel.addModel' })}
          visible={defaultVisible}
          onCancel={this.handleCancel}
          footer={null}
          width={800}
          destroyOnClose
        >
          <div style={{ marginBottom: "20px", display: 'flex', gap: '16px', alignItems: 'center' }}>
            <Input
              value={defaultQuery.search}
              placeholder={formatMessage({ id: 'largeModel.modalPlaceholder' })}
              style={{ width: '240px' }}
              onChange={e => onChangeModel(e.target.value)}
              onPressEnter={value => this.handleSearch(value)}
            />
            <Button type="primary" onClick={this.getModelList}>{formatMessage({ id: 'largeModel.modalSearch' })}</Button>
          </div>

          <Table
            columns={modelColumns}
            dataSource={defaultList}
            loading={defaultLoading}
            rowKey={'id'}
            pagination={false}
          />
        </Modal>
      </div>
    )
  }

  setMadelClick = () => {
    this.setState({ defaultVisible: true }, () => this.getModelList())
  }

  getModelList = async () => {
    const { applicationId } = this.props;
    let res = await getRobotModelList({ applicationId });
    console.log(res);
    this.setState({ defaultList: res })
  }

  onChangeModel = value => {
    let { defaultQuery } = this.state;
    defaultQuery.search = value;
    this.setState({ defaultQuery });
  }

  handleSearch = value => {
    let { defaultQuery } = this.state;
    defaultQuery.search = value;
    this.setState({ defaultQuery }, () => this.getModelList())
  }

  setAddModel = async row => {
    const { applicationId } = this.props;
    let res = await postRobotAdd({ applicationId, modelId: row.id });
    console.log(res);
    if (res.code == 0) {
      message.success(formatMessage({ id: 'largeModel.addSuccess' }));
      this.getList();
      this.getModelList();
    }
  }

  removeModel = async row => {
    const { applicationId } = this.props;
    let res = await getRobotRemove({ applicationId, modelId: row.id });
    console.log(res);
    if (res.code == 0) {
      message.success(formatMessage({ id: 'largeModel.removeSuccess' }));
      this.getList();
      this.getModelList();
    }
  }

  handleCancel = () => {
    this.setState({ defaultVisible: false })
  }

}

export default Form.create()(ModelList)